<template>
    <div class="form">
        <p class="title">手机号登录</p>
        <el-form :model="formData" status-icon :rules="formRules" ref="formRef" :show-message="false">
            <el-form-item prop="phone">
                <el-input v-model.trim="formData.phone" placeholder="输入手机号" maxLength="11"></el-input>
            </el-form-item>
            <el-form-item prop="verifyCode" class="none verifyCode">
                <el-input v-model.trim="formData.verifyCode" placeholder="输入验证码" maxLength="6"></el-input>
                <button type="button" class="codeBtn right disabled" v-if="isDisabled">发送验证码</button>
                <button type="button" class="codeBtn right" v-else @click="sendCode($event, time)">发送验证码</button>
            </el-form-item>
            <el-form-item class="none">
                <el-checkbox v-model="isRemember">
                    <span style="color: #666;">记住手机号</span>
                </el-checkbox>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="save('formRef')">登录</el-button>
            </el-form-item>
        </el-form>
        <!-- 其它登录方式 -->
        <div class="otherLogType">
            <span>其它登录方式：</span>
            <img src="../../assets/images/icon-wx.png" title="微信登录" alt="">
            <img src="../../assets/images/icon-qq.png" title="qq登录" alt="">
            <img src="../../assets/images/ulog.png" title="会员登录" alt="" @click="$store.commit('loginStore/updateStatus', 2)">
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            formData: {
                phone: this.isExitPhone() 
            },
            formRules: {
                phone: [{required: true, triggle: 'blur'}],
                verifyCode: [{required: true, triggle: 'blur'}]
            },
            isRemember: true,       //是否记住手机号
            isDisabled: this.isExitPhone() ? false : true,       //是否禁用验证码按钮
            isRunning: false,   //验证码是否正在倒计时
        }
    },
    computed: {
        time() {
            return this.$store.state.loginStore.time;
        }
    },
    watch: {
        'formData.phone'(newVal) {  //监听手机号码的位数
            if(this.isRunning) {
                //如果验证码正在倒计时，取消禁用状态
                this.isDisabled = false;
            } else {
                //如果验证码不在倒计时，判断手机号位数是否等于11位，不等于11位就禁用按钮点击
                newVal.length !== 11 ? this.isDisabled = true : this.isDisabled = false;
            }
        },
        isRunning(newVal) {
            if(newVal) {
                //如果验证码正在倒计时，取消禁用状态
                this.isDisabled = false;
            } else {
                //如果验证码不在倒计时，判断手机号位数是否等于11位，不等于11位就禁用按钮点击
                let phone = this.formData['phone'];
                phone.length !== 11 ? this.isDisabled = true : this.isDisabled = false;
            }
        }
    },
    methods: {
        isExitPhone() {     //判断缓存中是否存在phone
            let uInfo = JSON.parse(localStorage.getItem('uInfo'));
            if(uInfo && uInfo['phone']) {
                this.isDisabled = false;
                return uInfo['phone'];
            } else {
                return '';
            }
        },
        sendCode(ev, time) {        //发送验证码
            //发送验证码之前先校验手机号是否合法
            if(!this.$util.checkPhone(this.formData['phone'])) {
                this.$alert('手机号格式不正确', '注册提示', {
                    confirmButtonText: '确定'
                });
                return false;
            }
            //开始后台校验
            this.$http('verify/phoneLoginVerify?phone=' + this.formData['phone']).then(res => {
                if(res.data.code == 20001) {
                    this.$alert(res.data.data || '验证码发送成功', '登录提示', {
                        confirmButtonText: '确定'
                    });
                    let timer = null,
                        elem = ev.target;
                    timer = setInterval(() => {
                        if(time <= 1) {
                            clearInterval(timer);
                            elem.innerHTML = '发送验证码';
                            this.isRunning = false;
                        } else {
                            time--;
                            elem.innerHTML = time;
                            this.isRunning = true;
                        }
                    }, 1000);
                } else {
                    this.$alert(res.data.msg || '验证码发送失败', '登录提示', {
                        confirmButtonText: '确定'
                    });
                }
            });
        },
        save(formName) {        //登录
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if(!this.$util.checkPhone(this.formData['phone'])) {
                        this.$alert('手机号格式不正确', '注册提示', {
                            confirmButtonText: '确定'
                        });
                        return false;
                    }
                    //后台数据校验
                    this.$http({
                        url: '/login/loginPhone',
                        method: 'post',
                        params: this.formData
                    }).then(res => {
                        if(res.data.code == 20001) {
                            this.$notify({message: '登录成功', type: 'success', duration: '1500', offset: 30});
                            //存储登录信息
                            sessionStorage.setItem('isLogin', JSON.stringify(res.data.data));
                            if(this.isRemember) {
                                let uInfo = JSON.parse(localStorage.getItem('uInfo'));
                                if(uInfo) {
                                    uInfo['phone'] = this.formData['phone'];
                                    localStorage.setItem('uInfo', JSON.stringify(uInfo));
                                } else {
                                    //不存在时，创建uInfo对象
                                    localStorage.setItem('uInfo', JSON.stringify({phone: this.formData['phone']}));
                                }
                            } else {
                                let uInfo = JSON.parse(localStorage.getItem('uInfo'));
                                if(uInfo) {
                                    delete uInfo['phone'];
                                    if(JSON.stringify(uInfo) == '{}') {
                                        localStorage.removeItem('uInfo');
                                    } else {
                                        localStorage.setItem('uInfo', JSON.stringify(uInfo));
                                    }
                                } else {
                                    localStorage.removeItem('uInfo');
                                }
                            }
                            setTimeout(() => {
                                this.$router.push('/');     //跳转到首页
                            }, 1000);
                        } else {
                            this.$alert(res.data.msg || '登录失败', '登录提示', {
                                confirmButtonText: '确定'
                            });
                        }
                    });
                }
            });
        }
    }
}
</script>
<style scoped>
    .title {
        font-size: 16px;
        line-height: 1;
        text-align: center;
        padding: 15px 0;
    }
</style>